<?php

namespace App\Http\Controllers\Api;


use App\Models\PhoneCode;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Validation\Rule;
use JWTAuth;

class AuthController extends Controller
{
    //

    /**
     * 登录/注册
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        //验证用户输入
        $params = $request->only(['phone', 'code','type']);
        $validator = \Validator::make($params, [
            'phone' => 'required|regex:/^1[345789]\d{9}$/|size:11',
            'code' => 'required',
        ], [
            'phone.*' => '手机号码错误',
            'code.*' => '验证码错误',
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        $promo_code = $request->promo_code;

        //验证手机验证码问问23124441
        $re = PhoneCode::validation($request->phone, $request->code, 1);
        if (!$re) {
            return $this->error('验证码错误');
        }
        //查询用户
        $user = User::phoneUser($request->phone, $promo_code);
        //返回token
        $jwt_token = JWTAuth::fromUser($user);
        return $this->success(['token' => 'bearer ' . $jwt_token]);
    }

    /**
     * 获取验证码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCode(Request $request)
    {
        //验证用户输入
        $params = $request->only(['phone', 'type']);
        $validator = \Validator::make($params, [
            'phone' => 'required|regex:/^1[345789]\d{9}$/|size:11',
            'type'=>['required',Rule::in([1,2,3])]
        ], [
            'phone.*' => '手机号码错误',
            'type.required' => '类型不能为空',
            'type.in' => '值没在规定范围类',
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        //随机验证码
        $lower = 1000;
        $upper = 9999;
        $code = mt_rand($lower, $upper);

        //写入字段
        $data = [
            'phone' => $request->phone,
            'type' => $request->type,
            'code' => $code,
            'overdue_at' => date('Y-m-d H;i:s', strtotime('+5 minute'))
        ];

        $phone = $request->phone;
        if (\Cache::get('key') == $phone) {
            return $this->error('请一分钟后再获取');
        }
        \Cache::put('key', $phone, 1);
        $re = PhoneCode::add($data);
        if ($re) {
            return $this->success(['code' => $code, 'msg' => '发送成功']);
        }
        return $this->error('请再试一次 ');

    }


    public function test()
    {
        $data=[];
        for ($i = 1; $i <= 4; $i++) {
            for ($j = 1; $j <= 4; $j++) {
                for ($k = 1; $k <= 4; $k++) {
                        $data[]=$i.$j.$k;
                }
            }
        }

        dd($data);
    }

}
